#!/usr/bin/python
#
# this will grab just the binary payload and write it to $filedir/md5sum

import os
import sys
import datetime
import json
import hashlib
import logging
logging.basicConfig(level=logging.CRITICAL)

import hpfeeds

HOST = 'hpfeeds.honeycloud.net'
PORT = 10000
CHANNELS = ['mwbinary.dionaea.sensorunique',]
IDENT = ''
SECRET = ''
OUTFILE = './grabmw.log'
OUTDIR = './malware/'

def main():
    try: outfd = open(OUTFILE, 'a')
    except:
        print >>sys.stderr, 'could not open output file for message log.'
        return 1

    if not os.path.exists(OUTDIR): os.mkdir(OUTDIR)

    hpc = hpfeeds.new(HOST, PORT, IDENT, SECRET)
    print >>sys.stderr, 'connected to', hpc.brokername

    def on_message(identifier, channel, payload):
            # now store the file itself
            md5sum = hashlib.md5(payload).hexdigest()
            fpath = os.path.join(OUTDIR, md5sum)
            try:
                open(fpath, 'wb').write(payload)
            except:
                print >>outfd, '{0} ERROR could not write to {1}'.format(datetime.datetime.now().ctime(), fpath)
            outfd.flush()

    def on_error(payload):
        print >>sys.stderr, ' -> errormessage from server: {0}'.format(payload)
        hpc.stop()

    hpc.subscribe(CHANNELS)
    hpc.run(on_message, on_error)
    hpc.close()
    return 0

if __name__ == '__main__':
    try: sys.exit(main())
    except KeyboardInterrupt:sys.exit(0)

